<template>
  <div class="content-section wallet-section">
    <div class="section-header">
      <h2 class="section-title">我的钱包</h2>
    </div>
    <div class="wallet-overview">
      <div class="balance-card-new">
        <div class="balance-icon">💰</div>
        <div class="balance-info">
          <h3>账户余额</h3>
          <p class="balance-amount">¥{{ walletInfo.balance.toFixed(2) }}</p>
        </div>
      </div>
      <div class="wallet-actions">
        <button class="btn-primary" @click="showRecharge = true">
          <span class="btn-icon">💳</span>
          充值
        </button>
        <button class="btn-secondary" @click="showWithdraw = true">
          <span class="btn-icon">💸</span>
          提现
        </button>
      </div>
    </div>

    <div class="wallet-tabs">
      <div
        v-for="tab in walletTabs"
        :key="tab.key"
        :class="['wallet-tab', { active: activeWalletTab === tab.key }]"
        @click="activeWalletTab = tab.key"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 流水详情 -->
    <div
      v-show="activeWalletTab === 'transactions'"
      class="transactions-list"
      ref="transactionsList"
      @scroll="handleScroll"
    >
      <div v-for="transaction in transactions" :key="transaction.id" class="transaction-item">
        <div class="transaction-info">
          <p class="transaction-type">{{ transaction.description }}</p>
          <p class="transaction-time">{{ transaction.time }}</p>
        </div>
        <p :class="['transaction-amount', transaction.amount > 0 ? 'positive' : 'negative']">
          {{ transaction.amount > 0 ? '+' : '' }}¥{{ Math.abs(transaction.amount) }}
        </p>
      </div>
    </div>

    <!-- 收益分析 -->
    <div v-show="activeWalletTab === 'analytics'" class="analytics-section">
      <div class="chart-container">
        <div ref="chartRef" class="chart-wrapper"></div>
      </div>
      <div class="analytics-stats">
        <div class="stat-item">
          <div class="stat-label">本月收益</div>
          <div class="stat-value positive">+¥{{ monthlyEarnings.toFixed(2) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">总收益</div>
          <div class="stat-value positive">+¥{{ totalEarnings.toFixed(2) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">收益率</div>
          <div class="stat-value">{{ earningRate.toFixed(1) }}%</div>
        </div>
      </div>
    </div>
  </div>

  <!-- ==================== 弹窗组件 ==================== -->
  <!-- 充值弹窗 -->
  <div v-if="showRecharge" class="modal-overlay" @click="showRecharge = false">
    <div class="modal-content" @click.stop>
      <h3>账户充值</h3>
      <div class="recharge-options">
        <div
          v-for="amount in rechargeAmounts"
          :key="amount"
          :class="['amount-option', { selected: selectedAmount === amount && !isCustomAmount }]"
          @click="selectAmount(amount)"
        >
          ¥{{ amount }}
        </div>
        <div
          :class="['amount-option', 'custom-option', { selected: isCustomAmount }]"
          @click="selectCustomAmount"
        >
          自定义
        </div>
      </div>
      <div v-if="isCustomAmount" class="form-group">
        <label>自定义金额</label>
        <input
          v-model="customRechargeAmount"
          type="number"
          class="form-input"
          placeholder="请输入充值金额"
          min="1"
          step="0.01"
        />
      </div>
      <div class="modal-actions">
        <button class="btn-secondary" @click="showRecharge = false">取消</button>
        <button class="btn-primary" @click="recharge" :disabled="!canRecharge">
          确认充值 ¥{{ finalRechargeAmount }}
        </button>
      </div>
    </div>
  </div>

  <!-- 提现弹窗 -->
  <div v-if="showWithdraw" class="modal-overlay" @click="showWithdraw = false">
    <div class="modal-content" @click.stop>
      <h3>账户提现</h3>
      <div class="form-group">
        <label>提现金额</label>
        <input
          v-model="withdrawAmount"
          type="number"
          class="form-input"
          placeholder="请输入提现金额"
        />
      </div>
      <div class="modal-actions">
        <button class="btn-secondary" @click="showWithdraw = false">取消</button>
        <button class="btn-primary" @click="withdraw">确认提现</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, Ref } from 'vue';
  import { useECharts } from '@/hooks/web/useECharts';
  import { getWalletInfoApi, getTransactionApi } from '@/api/system/user';

  // ==================== 响应式数据 ====================
  const activeWalletTab = ref('transactions');
  const showRecharge = ref(false);
  const showWithdraw = ref(false);
  const selectedAmount = ref(100);
  const withdrawAmount = ref('');
  const chartRef = ref<HTMLDivElement | null>(null);
  const isCustomAmount = ref(false);
  const customRechargeAmount = ref('');
  const transactionsList = ref(null);

  // 钱包信息
  const walletInfo = ref({
    balance: 0,
  });

  const walletTabs = [
    { key: 'transactions', label: '流水详情' },
    { key: 'analytics', label: '收益分析' },
  ];

  async function getWalletInfo() {
    try {
      const data = await getWalletInfoApi();
      walletInfo.value = data;
    } catch (error) {
      console.error('error:', error);
    }
  }

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const loading = ref(false);
  const isLastPage = ref(false);
  const transactions = ref<any[]>([]);

  async function loadData(isRefresh = false) {
    if (loading.value || (isLastPage.value && !isRefresh)) return;

    loading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
      };

      const data: any = await getTransactionApi(params);

      let list = data.records || [];

      if (isRefresh) {
        transactions.value = list;
      } else {
        transactions.value = [...transactions.value, ...list];
      }

      if (list.length < 10) {
        isLastPage.value = true;
      }

      if (!isLastPage.value) {
        pageNum.value = data.current;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      loading.value = false;
    }
  }

  function resetPage() {
    pageNum.value = 1;
    isLastPage.value = false;
    transactions.value = [];
  }

  const handleScroll = () => {
    if (!transactionsList.value) return;

    const { scrollTop, scrollHeight, clientHeight } = transactionsList.value;

    // 当滚动到距离底部50px时触发加载
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      loadData();
    }
  };

  // const transactions = ref([
  //   { id: 1, type: '课程购买', amount: -99, time: '2024-01-15 10:30' },
  //   { id: 2, type: '账户充值', amount: 200, time: '2024-01-14 16:20' },
  //   { id: 3, type: '提现', amount: -150, time: '2024-01-13 09:15' },
  //   { id: 4, type: '课程收益', amount: 88, time: '2024-01-12 14:30' },
  //   { id: 5, type: '推荐奖励', amount: 25, time: '2024-01-11 09:45' },
  //   { id: 6, type: '课程购买', amount: -199, time: '2024-01-10 16:20' },
  // ]);

  // 收益统计数据
  const monthlyEarnings = ref(113);
  const totalEarnings = ref(1256.8);
  const earningRate = ref(12.5);

  // 收益图表数据
  const earningsData = ref([
    { month: '1月', earnings: 120, expenses: 80 },
    { month: '2月', earnings: 150, expenses: 120 },
    { month: '3月', earnings: 180, expenses: 90 },
    { month: '4月', earnings: 200, expenses: 150 },
    { month: '5月', earnings: 160, expenses: 110 },
    { month: '6月', earnings: 220, expenses: 180 },
    { month: '7月', earnings: 190, expenses: 140 },
    { month: '8月', earnings: 250, expenses: 200 },
    { month: '9月', earnings: 210, expenses: 160 },
    { month: '10月', earnings: 280, expenses: 220 },
    { month: '11月', earnings: 240, expenses: 190 },
    { month: '12月', earnings: 300, expenses: 250 },
  ]);

  const rechargeAmounts = [50, 100, 200, 500, 1000];

  const finalRechargeAmount = computed(() => {
    if (isCustomAmount.value) {
      return parseFloat(customRechargeAmount.value) || 0;
    }
    return selectedAmount.value;
  });

  const canRecharge = computed(() => {
    return finalRechargeAmount.value > 0;
  });

  const selectAmount = (amount) => {
    selectedAmount.value = amount;
    isCustomAmount.value = false;
    customRechargeAmount.value = '';
  };

  const selectCustomAmount = () => {
    isCustomAmount.value = true;
    selectedAmount.value = 0;
  };

  const recharge = () => {
    if (!canRecharge.value) return;

    walletInfo.value.balance += finalRechargeAmount.value;
    showRecharge.value = false;

    isCustomAmount.value = false;
    customRechargeAmount.value = '';
    selectedAmount.value = 100;

    console.log(`充值 ¥${finalRechargeAmount.value} 成功`);
  };

  const withdraw = () => {
    if (withdrawAmount.value && withdrawAmount.value <= walletInfo.value.balance) {
      walletInfo.value.balance -= parseFloat(withdrawAmount.value);
      showWithdraw.value = false;
      withdrawAmount.value = '';
      console.log('提现成功');
    }
  };

  // ECharts 配置
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

  const initChart = () => {
    if (!chartRef.value) return;

    const months = earningsData.value.map((item) => item.month);
    const earnings = earningsData.value.map((item) => item.earnings);
    const expenses = earningsData.value.map((item) => item.expenses);

    setOptions({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
        formatter: function (params: any) {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach((param: any) => {
            result += `${param.marker}${param.seriesName}: ¥${param.value}<br/>`;
          });
          return result;
        },
      },
      legend: {
        data: ['收益', '支出'],
        top: 10,
        textStyle: {
          color: '#666',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: months,
        axisPointer: {
          type: 'shadow',
        },
        axisLabel: {
          color: '#666',
          fontSize: 12,
        },
        axisLine: {
          lineStyle: {
            color: '#e0e0e0',
          },
        },
      },
      yAxis: {
        type: 'value',
        name: '金额 (¥)',
        nameTextStyle: {
          color: '#666',
        },
        axisLabel: {
          color: '#666',
          fontSize: 12,
          formatter: '¥{value}',
        },
        axisLine: {
          lineStyle: {
            color: '#e0e0e0',
          },
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed',
          },
        },
      },
      series: [
        {
          name: '收益',
          type: 'line',
          smooth: true,
          data: earnings,
          lineStyle: {
            color: '#50c878',
            width: 3,
          },
          itemStyle: {
            color: '#50c878',
            borderWidth: 2,
            borderColor: '#fff',
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(80, 200, 120, 0.3)',
                },
                {
                  offset: 1,
                  color: 'rgba(80, 200, 120, 0.05)',
                },
              ],
            },
          },
          emphasis: {
            focus: 'series',
          },
        },
        {
          name: '支出',
          type: 'line',
          smooth: true,
          data: expenses,
          lineStyle: {
            color: '#ef4444',
            width: 3,
          },
          itemStyle: {
            color: '#ef4444',
            borderWidth: 2,
            borderColor: '#fff',
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(239, 68, 68, 0.3)',
                },
                {
                  offset: 1,
                  color: 'rgba(239, 68, 68, 0.05)',
                },
              ],
            },
          },
          emphasis: {
            focus: 'series',
          },
        },
      ],
    });
  };

  onMounted(() => {
    getWalletInfo();
    loadData();
    initChart();
  });
</script>

<style lang="less">
  //钱包
  .wallet-overview {
    display: flex;
    align-items: stretch;
    gap: 24px;
    margin-bottom: 24px;
    flex-wrap: wrap;

    .balance-card-new {
      background: linear-gradient(135deg, #4a90e2, #50c878);
      color: white;
      padding: 24px 28px;
      border-radius: 16px;
      display: flex;
      align-items: center;
      gap: 20px;
      box-shadow: 0 8px 32px rgba(80, 200, 120, 0.25);
      flex: 1;
      min-width: 320px;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100%;
        height: 100%;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
        pointer-events: none;
      }

      .balance-icon {
        font-size: 36px;
        opacity: 0.95;
        filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
      }

      .balance-info {
        flex: 1;
        position: relative;
        z-index: 1;

        h3 {
          margin: 0 0 8px;
          font-size: 16px;
          opacity: 0.95;
          font-weight: 500;
          letter-spacing: 0.5px;
        }

        .balance-amount {
          margin: 0;
          font-size: 32px;
          font-weight: 800;
          text-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
          letter-spacing: -0.5px;
        }
      }
    }

    .wallet-actions {
      display: flex;
      flex-direction: column;
      gap: 12px;
      flex-shrink: 0;
      min-width: 120px;

      .btn-primary,
      .btn-secondary {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 14px 20px;
        font-size: 14px;
        border-radius: 12px;
        font-weight: 600;
        white-space: nowrap;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        min-height: 48px;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 100%;
          background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
          transition: left 0.5s ease;
        }

        &:hover::before {
          left: 100%;
        }

        .btn-icon {
          font-size: 18px;
          transition: transform 0.3s ease;
        }

        &:hover .btn-icon {
          transform: scale(1.1);
        }
      }

      .btn-primary {
        background: linear-gradient(135deg, #3b82f6, #1d4ed8);
        color: white;
        border: none;
        box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3);

        &:hover {
          background: linear-gradient(135deg, #2563eb, #1e40af);
          box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4);
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(0);
        }
      }

      .btn-secondary {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
        border: none;
        box-shadow: 0 4px 16px rgba(245, 158, 11, 0.3);

        &:hover {
          background: linear-gradient(135deg, #d97706, #b45309);
          box-shadow: 0 6px 20px rgba(245, 158, 11, 0.4);
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }

  .wallet-tabs {
    display: flex;
    margin-bottom: 20px;
    border-bottom: 1px solid #e2e8f0;

    .wallet-tab {
      padding: 12px 20px;
      cursor: pointer;
      border-bottom: 2px solid transparent;
      transition: all 0.3s;
      color: #64748b;

      &:hover {
        color: #50c878;
      }

      &.active {
        color: #50c878;
        border-bottom-color: #50c878;
      }
    }
  }

  .transactions-list {
    max-height: 450px;
    overflow-y: auto;
    padding-right: 8px;

    .transaction-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f1f5f9;

      &:last-child {
        border-bottom: none;
      }

      .transaction-info {
        flex: 1;
        min-width: 0;

        .transaction-type {
          margin: 0 0 4px;
          font-weight: 500;
          color: #1e293b;
          font-size: 14px;
        }

        .transaction-time {
          margin: 0;
          font-size: 12px;
          color: #64748b;
        }
      }

      .transaction-amount {
        font-weight: 600;
        font-size: 14px;
        flex-shrink: 0;
        margin-left: 12px;

        &.positive {
          color: #50c878;
        }

        &.negative {
          color: #ef4444;
        }
      }
    }
  }

  .analytics-section {
    .chart-container {
      background: #f8fafc;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 20px;
      max-width: 100%;
      overflow: hidden;

      .chart-wrapper {
        width: 100%;
        height: 350px;
        min-height: 350px;
        max-width: 100%;
      }
    }

    .analytics-stats {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
      gap: 12px;
      max-width: 100%;

      .stat-item {
        background: white;
        padding: 16px;
        border-radius: 10px;
        text-align: center;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
        border: 1px solid #f1f5f9;
        min-width: 0;

        .stat-label {
          font-size: 13px;
          color: #64748b;
          margin-bottom: 6px;
          font-weight: 500;
        }

        .stat-value {
          font-size: 18px;
          font-weight: 700;
          color: #1e293b;
          word-break: break-all;

          &.positive {
            color: #50c878;
          }

          &.negative {
            color: #ef4444;
          }
        }
      }
    }
  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .modal-content {
      background: white;
      border-radius: 12px;
      padding: 24px;
      width: 90%;
      max-width: 400px;

      h3 {
        margin: 0 0 20px;
        font-size: 20px;
        font-weight: 600;
        color: #1e293b;
      }

      .recharge-options {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
        margin-bottom: 20px;

        .amount-option {
          padding: 12px;
          border: 1px solid #e2e8f0;
          border-radius: 8px;
          text-align: center;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            border-color: #50c878;
          }

          &.selected {
            border-color: #50c878;
            background-color: rgba(80, 200, 120, 0.1);
            color: #50c878;
          }
        }

        .custom-option {
          background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
          font-weight: 600;

          &.selected {
            background: linear-gradient(135deg, #4a90e2, #50c878);
            color: white;
            border-color: #50c878;
          }
        }
      }

      .modal-actions {
        display: flex;
        gap: 12px;
        justify-content: flex-end;
      }
    }
  }

  // 移动端响应式样式
  @media (max-width: 768px) {
    .wallet-overview {
      flex-direction: column;
      align-items: stretch;
      gap: 20px;
      margin-bottom: 20px;

      .balance-card-new {
        padding: 20px 24px;
        min-width: auto;
        border-radius: 14px;

        .balance-icon {
          font-size: 32px;
        }

        .balance-info {
          h3 {
            font-size: 15px;
          }

          .balance-amount {
            font-size: 28px;
          }
        }
      }

      .wallet-actions {
        flex-direction: row;
        gap: 12px;
        min-width: auto;

        .btn-primary,
        .btn-secondary {
          padding: 12px 18px;
          font-size: 13px;
          flex: 1;
          min-height: 44px;

          .btn-icon {
            font-size: 16px;
          }
        }
      }
    }

    .wallet-tabs {
      margin-bottom: 16px;

      .wallet-tab {
        padding: 10px 16px;
        font-size: 14px;
      }
    }

    .transactions-list {
      max-height: 400px;

      .transaction-item {
        padding: 10px 0;

        .transaction-info {
          .transaction-type {
            font-size: 13px;
          }

          .transaction-time {
            font-size: 11px;
          }
        }

        .transaction-amount {
          font-size: 13px;
        }
      }
    }

    .analytics-section {
      .chart-container {
        padding: 12px;
        margin-bottom: 16px;

        .chart-wrapper {
          height: 300px;
          min-height: 300px;
        }
      }

      .analytics-stats {
        grid-template-columns: 1fr;
        gap: 10px;

        .stat-item {
          padding: 14px;

          .stat-label {
            font-size: 12px;
          }

          .stat-value {
            font-size: 16px;
          }
        }
      }
    }
  }

  // 超小屏幕优化
  @media (max-width: 480px) {
    .wallet-overview {
      gap: 16px;

      .balance-card-new {
        padding: 18px 20px;
        gap: 16px;
        border-radius: 12px;

        .balance-icon {
          font-size: 28px;
        }

        .balance-info {
          h3 {
            font-size: 14px;
          }

          .balance-amount {
            font-size: 24px;
          }
        }
      }

      .wallet-actions {
        gap: 10px;

        .btn-primary,
        .btn-secondary {
          padding: 10px 14px;
          font-size: 12px;
          min-height: 40px;
          border-radius: 10px;

          .btn-icon {
            font-size: 14px;
          }
        }
      }
    }

    .transactions-list {
      max-height: 350px;
    }

    .analytics-section {
      .chart-container {
        .chart-wrapper {
          height: 250px;
          min-height: 250px;
        }
      }
    }
  }
</style>
